package org.guegan.util.dircompare.swt;

import java.util.Date;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.guegan.util.dircompare.main.ProgressionCallbackListener;

public 	class ScanActionListener implements ProgressionCallbackListener {
	private int state = 0;
	private Composite parent;
	private ProgressBar pb;
	private Date startDate;
	private Date latestDisplay;

	private Runnable asynchAction = new Runnable() {
		public void run() {
			if (pb.isDisposed())
				return;
			pb.setSelection(++state);
			Date now = new Date();
			if (now.getTime() - latestDisplay.getTime() > 1000) {
				int diff = (int) ((now.getTime() - startDate.getTime()) / 1000L);
				Double target = 1D * diff * pb.getMaximum() / state;
				Double remaining = target - diff;
				StringBuilder sb = new StringBuilder();
				asMinutes(diff, sb);
				sb.append(" from the start. ");
				asMinutes(remaining.intValue(), sb);
				sb.append(" remaining (");
				asMinutes(target.intValue(), sb);
				sb.append(")");
				pb.setToolTipText(sb.toString());
				latestDisplay = now;
			}
		}
	};
	
	private void asMinutes(int seconds, StringBuilder sb) {
		int min = seconds / 60;
		seconds -= min * 60;
		sb.append(min).append(":");
		if (seconds < 10) {
			sb.append("0");
		}
		sb.append(seconds);
	}
	
	public ScanActionListener(Composite shell, ProgressBar pb) {
		this.parent = shell;
		this.pb = pb;
		this.startDate = new Date();
		this.latestDisplay = startDate;
	}

	@Override
	public boolean progressionCallback(boolean isScanned) {
		if (isScanned && !parent.isDisposed()) {
			Display display = parent.getDisplay();
			display.asyncExec(asynchAction);
		}
		return false;
	}
}

